const axios = require('axios');
const query = require('../../utils/query'); // 假设这是你的数据库查询工具

class VoiceTokenService {
  constructor(clientId, clientSecret) {
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.voiceToken = null; // 内存中缓存的语音 Token
    this.voiceTokenExpireTime = 0; // 语音 Token 的过期时间戳
  }

  /**
   * 从数据库获取语音 Token
   */
  async getVoiceTokenFromDatabase() {
    const sql = `SELECT * FROM tokens WHERE name = 'voice_token' LIMIT 1`;
    const result = await query(sql);
    if (result.length > 0) {
      const tokenData = result[0];
      const now = Date.now();
      if (new Date(tokenData.expires_at).getTime() > now) {
        // 数据库中的语音 Token 未过期
        this.voiceToken = tokenData.access_token;
        this.voiceTokenExpireTime = new Date(tokenData.expires_at).getTime();
        return this.voiceToken;
      }
    }
    return null; // 数据库中的语音 Token 不存在或已过期
  }

  /**
   * 保存或更新语音 Token 到数据库
   */
  async saveVoiceTokenToDatabase(accessToken, expiresIn) {
    const expiresAt = new Date(Date.now() + expiresIn * 1000); // 计算过期时间
    const sql = `
      INSERT INTO tokens (name, access_token, expires_at) 
      VALUES ('voice_token', ?, ?) 
      ON DUPLICATE KEY UPDATE 
      access_token = VALUES(access_token), 
      expires_at = VALUES(expires_at), 
      updated_at = CURRENT_TIMESTAMP
    `;
    await query(sql, [accessToken, expiresAt]);
  }

  /**
   * 从百度接口获取新的语音 Token
   */
  async fetchVoiceTokenFromBaidu() {
    const response = await axios.get('https://aip.baidubce.com/oauth/2.0/token', {
      params: {
        grant_type: 'client_credentials',
        client_id: this.clientId,
        client_secret: this.clientSecret,
      },
    });

    if (response.data && response.data.access_token) {
      const { access_token, expires_in } = response.data;
      
      this.voiceToken = access_token;
      this.voiceTokenExpireTime = Date.now() + expires_in * 1000; // 更新内存中的过期时间
      await this.saveVoiceTokenToDatabase(access_token, expires_in); // 保存到数据库
      return this.voiceToken;
    } else {
      throw new Error('Failed to fetch voice token. No access_token in response.');
    }
  }

  /**
   * 获取语音 Token（优先从内存，其次从数据库，再次从百度接口）
   */
  async getVoiceToken() {
    const now = Date.now();

    // 内存中的语音 Token 有效
    if (this.voiceToken && now < this.voiceTokenExpireTime) {
      return this.voiceToken;
    }

    // 从数据库获取语音 Token
    const dbToken = await this.getVoiceTokenFromDatabase();
    if (dbToken) {
      return dbToken;
    }

    // 从百度接口获取新的语音 Token
    return this.fetchVoiceTokenFromBaidu();
  }
}

module.exports = VoiceTokenService;
